package com.guanzhi.controller;

import com.alibaba.fastjson2.JSONObject;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Redis 使用
 * <p> Package: com.guanzhi.controller </p>
 * <p> File: RedisController.java </p>
 * <p> Description:  (Redis 接口)</p>
 * <p> Date: 2024/2/23 17:23</p>
 *
 * @author 观之
 * @version 1.0 （代码版本）
 * @email <a href="mailto:guanzhi55634@aliyun.com">观之</a>（邮箱）
 * @date 2024/2/23 17:23
 * @since jdk17（jdk版本）
 */
@RestController
@AllArgsConstructor
public class RedisController {

    /**
     * RedisTemplate 对象
     */
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置缓存
     *
     * @param key   缓存Key
     * @param value 缓存值
     */
    @RequestMapping(value = "/set", method = RequestMethod.POST)
    public String set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
        return "成功";
    }

    /**
     * 查询缓存
     *
     * @param key 缓存Key
     * @return 缓存值
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public String get(String key) {
        if (!Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            return "查询失败,当前查询缓存主键不存在！";
        }
        Object keyValueObject = redisTemplate.opsForValue().get(key);
        if (keyValueObject != null) {
            JSONObject jsonObject = JSONObject.parseObject(keyValueObject.toString());
            return jsonObject.toString();
        }
        return "查询失败";
    }
}
